package cn.yunhe.dao.impl;

import cn.yunhe.dao.RecordDao;
import cn.yunhe.pojo.Record;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class RecordDaoImpl extends HibernateDaoSupport implements RecordDao {
    @Override
    public boolean insertRecord(Record record) {
        getHibernateTemplate().save(record);
        return false;
    }

    @Override
    public boolean updateRecord(Record record) {
        getHibernateTemplate().update(record);
        return false;
    }

    @Override
    public boolean deleteRecord(int id) {
        getHibernateTemplate().delete(this.getById(id));
        return false;
    }

    @Override
    public Record getById(int id) {
        Record record=getHibernateTemplate().get(Record.class,id);
        return record;
    }

    @Override
    public List<Record> findRecord(String hql) {
        List<Record>recordList=getHibernateTemplate().find(hql);
        return recordList;
    }

    @Override
    public List<Record> findRecord(final Record record) {
        List<Record>recordList=getHibernateTemplate().executeFind(new HibernateCallback<List<Record>>() {
            @Override
            public List<Record> doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria=session.createCriteria(Record.class);
                if (record!=null){
                    if (record.getId()>0){
                        criteria.add(Restrictions.eq("id",record.getId()));
                    }
                    if (record.getRmoney()!=null&&record.getRmoney()>0){
                        criteria.add(Restrictions.gt("rmoney",record.getRmoney()));
                    }
                    if (record.getRdate()!=null&&!record.getRdate().equals("")){
                        criteria.add(Restrictions.like("rdate",record.getRdate(),MatchMode.ANYWHERE));
                    }
                    if (record.getRmark()!=null&&!record.getRmark().equals("")){
                        criteria.add(Restrictions.like("rmark",record.getRmark(),MatchMode.ANYWHERE));
                    }
                }
                List<Record>recordList111=criteria.list();
                return recordList111;
            }
        });
        return recordList;
    }
}
